package com.ali.gts.servlet.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionServlet  extends BaseServlet{

    protected void crateAndGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       HttpSession httpSession = req.getSession();
       //判断当前session是否是新创建出来的,特别注意这里代码每次用谷歌浏览器调用时
       // 每次都是新的,苹果浏览器第一次时true,以后都是false
       boolean isNew = httpSession.isNew();
       //获取当前Session的唯一ID
       String id = httpSession.getId();

       resp.getWriter().write("得到的Session,它的id 是"+id+"<br/>");
       resp.getWriter().write("这个Session是否是新建的"+isNew+"<br/>");


    }
    //向session中存数据
    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("key1","val1");
        resp.getWriter().write("已经 向session中 存储了数据");
    }
    //往session 中取数据
    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       Object attribute = req.getSession().getAttribute("key1");
       resp.getWriter().write("获取到的值是"+attribute);

    }
    //session默认的超时时间，可以通过配置的方式设置session的超时时间
    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int time = req.getSession().getMaxInactiveInterval();

        resp.getWriter().write("Session默认的超时时长为"+time+"秒");

    }

    //立即删除session
    protected void deleteSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getSession().invalidate();

        resp.getWriter().write("Session已经设置为超时 无效");


    }








}
